/**
 * 
 */
package com.brewdroid.db.dao;

import java.util.ArrayList;

import android.content.ContentValues;
import android.database.Cursor;

import com.brewdroid.db.DatabaseHelper;
import com.brewdroid.model.Adjunct;

/**
 * @author meeusen
 *
 */
public class AdjunctDAO {
	
	private static final String TABLE="adjunct";
	private static final String NULL_COL="name";
	private static final String ADJUNCT_SELECT_BY_ID="select * from adjunct where _id=?";
	private static final String ADJUNCT_SELECT_ALL="select * from adjunct order by name";
	private static final String ADJUNCT_SELECT_ID="select a._id from adjunct a where a.description=? and a.name=? and a.purpose=?";
	private static final String ADJUNCT_SELECL_BY_NAME="select * from adjunct where name=?";
	
	public static Adjunct getAdjunctById(DatabaseHelper db, int id)
	{
		Cursor c =db.getReadableDatabase().rawQuery(ADJUNCT_SELECT_BY_ID, new String[]{Integer.toString(id)});
		c.moveToFirst();
		Adjunct a = makeAdjunctFromCursor(c);
		
		return a;
	}
	
	public static Adjunct getAdjunctByName(DatabaseHelper db, String name)
	{
		Adjunct a =null;
		Cursor c= db.getReadableDatabase().rawQuery(ADJUNCT_SELECL_BY_NAME, new String []{name});
		if (c.moveToFirst())
			a =makeAdjunctFromCursor(c);
		
		return a;
	}
	
	public static ArrayList<Adjunct> getAdjuncts(DatabaseHelper db)
	{
		ArrayList<Adjunct> adjs = new ArrayList<Adjunct>();
		Cursor c = db.getReadableDatabase().rawQuery(ADJUNCT_SELECT_ALL, new String[]{});
		if(c.moveToFirst())
		{
			do{
				Adjunct a = makeAdjunctFromCursor(c);
				adjs.add(a);
				
			}while(c.moveToNext());
		}
		return adjs;
	}
	
	public static ArrayList<String> getAdjunctStrings(DatabaseHelper dbHelper) {
		ArrayList<String> adjunctStrings = new ArrayList<String>();
		for(Adjunct i: getAdjuncts(dbHelper)){
			adjunctStrings.add(i.getName());
		}
		
		return adjunctStrings;
	}

	public static void addAdjunct(DatabaseHelper db, Adjunct adjunct)
	{
		if(getId(db, adjunct)==0)	//don't want to re-insert it if its already there
		{
			ContentValues cv = new ContentValues();
			cv.put("description", adjunct.getDescription());
			cv.put("name", adjunct.getName());
			cv.put("purpose", adjunct.getPurpose());
			
			db.getWritableDatabase().insert(TABLE, NULL_COL, cv);
		}
	}
	
	public static int getId(DatabaseHelper db, Adjunct adjunct)
	{
		Cursor c = db.getReadableDatabase().rawQuery(ADJUNCT_SELECT_ID, new String[]{
																			adjunct.getDescription(),
																			adjunct.getName(),
																			adjunct.getPurpose()
		});
		
		return c.moveToFirst()?c.getInt(0):0;
	}
	
	private static Adjunct makeAdjunctFromCursor(Cursor c) {
		
		Adjunct a = new Adjunct();
		a.setDescription(c.getString(1));
		a.setName(c.getString(2));
		a.setPurpose(c.getString(3));
		
		return a;
	}


}
